//
//  AISettingController.m
//  Mia
//
//  Created by Vill on 2024/1/12.
//

#import "AISettingController.h"
#import "AIGradientTabView.h"
#import "AISetListNormalCell.h"   //设置
#import "AISettingSwitchCell.h"   //switch
#import "AIWalletTitleView.h"  // 标题
#import "UIApplication+Extension.h"
#import "AppDelegate.h"
#import "AISetBalanceListCell.h"     //钱包
#import "AISetVipGetCell.h"          //设置VIP
#import "AISetVipInfoShowCell.h"     //展示VIP详情
#import "AISetIconNameCell.h"        //个人资料
#import "AISettingSwitchCell.h"      //开关
#import "AISetLogOutView.h"          //logout
#import <SafariServices/SafariServices.h>
#import "AIFeedbackController.h"     //feedback
#import "AIPersonalInfoController.h" //profile
#import "AIWalletController.h"       //钱包
#import "AIVipPlusController.h"      //vip
#import "AICommonWebController.h"  //协议
#import "AISetLogoutAlertView.h"

@interface AISettingController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UIVisualEffectView *blurView; //模糊
@property (nonatomic, strong) UIButton *closeBtn;
@property (nonatomic, strong) AIGradientTabView *tableView;
@property (nonatomic, strong) AIWalletTitleView *titView;  //标题

@property (nonatomic, strong) AISetLogOutView *logOutView;

@end

@implementation AISettingController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // 模糊
    [self.view addSubview:self.blurView];
    [self.blurView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(self.view);
    }];
    // 关闭
    [self.view addSubview:self.closeBtn];
    [self.closeBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(PTW(34));
        make.trailing.mas_equalTo(self.view).mas_offset(-PTW(12.5));
        make.top.mas_equalTo(self.view).mas_offset(KStatusBarHeight + PTW(5));
    }];
    [self.view addSubview:self.tableView];
}

#pragma mark --------------- uitableviewdelegate,UITableViewDataSource ---------------
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
//    return 4;
    return 3;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    if(section == 0){
//        return 4;
//    }else if (section == 1){
//        return 2;
//    }else if (section == 2){
//        return 4;
//    }else{
//        return 2;
//    }
    if(section == 0){
        return 4;
    }else if (section == 1){
        return 4;
    }else{
        return 2;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        if (indexPath.row == 0){
            AISetBalanceListCell *cell = [AISetBalanceListCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            return cell;
        }else if (indexPath.row == 1){
            AIUserInfoModel *model = [[AIUserInfoManager shareManager] userInfo];
            if (model.vip){
                AISetVipInfoShowCell *cell = [AISetVipInfoShowCell cellWithTableView:tableView];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }else{
                AISetVipGetCell *cell = [AISetVipGetCell cellWithTableView:tableView];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                return cell;
            }
        }else if (indexPath.row == 2){
            AISetIconNameCell *cell = [AISetIconNameCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            AIUserInfoModel *userInfo = [AIUserInfoManager shareManager].userInfo;
            [cell setIconImg:@"" withName:userInfo.nickName];
            return cell;
        }else{
            AISetListNormalCell *cell = [AISetListNormalCell cellWithTableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.leftLbl.text = @"Personal information";
            return cell;
        }
//    }else if (indexPath.section == 1){
//        AISettingSwitchCell *cell = [AISettingSwitchCell cellWithTableView:tableView];
//        cell.selectionStyle = UITableViewCellSelectionStyleNone;
//        if (indexPath.row == 0){
//            cell.leftLbl.text = @"Background music";
//        }else{
//            cell.leftLbl.text = @"Notification";
//        }
//        return cell;
//    }else if (indexPath.section == 2){
    }else if (indexPath.section == 1){
        AISetListNormalCell *cell = [AISetListNormalCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0){
            cell.leftLbl.text = @"Feedback";
        }else if (indexPath.row == 1){
            cell.leftLbl.text = @"About us";
            cell.rightLbl.text = [NSString stringWithFormat:@"Version%@",UIApplication.sharedApplication.appVersion];
        }else if (indexPath.row == 2){
            cell.leftLbl.text = @"Clear cache";
            // 清除缓存
            NSUInteger total = [SDImageCache sharedImageCache].totalDiskSize;
            if (total > 0){
                cell.rightLbl.text = [NSString stringWithFormat:@"%.2fM",total/1024.f/1024.f];
            }else{
                cell.rightLbl.text = @"0M";
            }
        }else{
            cell.leftLbl.text = @"Delete the account";
        }
        return cell;
    }else{
        AISetListNormalCell *cell = [AISetListNormalCell cellWithTableView:tableView];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        if (indexPath.row == 0){
            cell.leftLbl.text = @"Terms of Service";
        }else{
            cell.leftLbl.text = @"Privacy Policy";
        }
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        if (indexPath.row == 0){
            // 金币
            AIWalletController *vc = [[AIWalletController alloc] init];
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        }else if (indexPath.row == 1){
            // vip
            AIVipPlusController *vc = [[AIVipPlusController alloc] init];
            vc.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:vc animated:YES completion:nil];
        }else if (indexPath.row == 2){
            
        }else{
            AIPersonalInfoController *proInfo = [AIPersonalInfoController new];
            [self.navigationController pushViewController:proInfo animated:YES];
        }
//    }else if (indexPath.section == 1){
//        
//    }else if (indexPath.section == 2){
    }else if (indexPath.section == 1){
        if (indexPath.row == 0){
            // feedback
            AIFeedbackController *feedback = [AIFeedbackController new];
//            feedback.modalPresentationStyle = UIModalPresentationOverFullScreen;
//            [self presentViewController:feedback animated:YES completion:nil];
            [self.navigationController pushViewController:feedback animated:YES];
        }else if (indexPath.row == 1){
            //about us
        }else if (indexPath.row == 2){
            //clear cache
            [MBProgressTool mb_showHUDInView:self.view];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
                    [MBProgressTool mb_hideHUDInView:self.view];
                    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:1]] withRowAnimation:UITableViewRowAnimationFade];
                }];
            });
        }else{
            //delete account
            AISetLogoutAlertView *logout = [[AISetLogoutAlertView alloc] initWithType:0];
            [logout showInView:self.view];
            WeakSelf(self);
            logout.confirmBlock = ^{
                [weakself deleteTheAccount];
            };
        }
    }else{
        if (indexPath.row == 0){
            [self policyAction:1];
        }else{
            [self policyAction:2];
        }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0){
        if (indexPath.row == 0){
            return PTW(105);
        }else if (indexPath.row == 1){
            AIUserInfoModel *model = [[AIUserInfoManager shareManager] userInfo];
            if (model.vip){
                return PTW(116);
            }else{
                return PTW(160);
            }
        }else if (indexPath.row == 2){
            return PTW(88);
        }else{
            return PTW(68);
        }
    }
    return PTW(68);
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    // 创建一个空的footerView
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, PTW(2), KScreenWidth, PTW(21))];
    UILabel *line = [[UILabel alloc] initWithFrame:CGRectMake(0, PTW(10), KScreenWidth, PTW(1))];
    line.backgroundColor = [UIColor colorHex:@"#000000" alpha:0.05];
    [view addSubview:line];
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    // 设置footerView的高度为0.01
    return PTW(21);
}

// 协议
-(void)policyAction:(NSInteger)type{
//    // 创建一个 SFSafariViewController 对象并指定要打开的网页链接
//    NSString *str = type == 1 ? kTermsService:kPrivacyPolicy;
//    NSURL *url = [NSURL URLWithString:str];
//    SFSafariViewController *safariVC = [[SFSafariViewController alloc] initWithURL:url];
////    // 设置 SFSafariViewController 的代理（可选）
////    safariVC.delegate = self;
//    safariVC.modalPresentationStyle = UIModalPresentationFullScreen;
//    [self presentViewController:safariVC animated:YES completion:nil];
    AICommonWebController *web = [[AICommonWebController alloc] init];
    web.isTerms = type == 1 ? YES:NO;
    [self.navigationController pushViewController:web animated:YES];
}

#pragma mark -------------- delete And logout ------------
// 删除账号
- (void)deleteTheAccount{
    [SVProgressHUD show];
    [AIManager requestMethod:@"GET" url:api_customRepeal parameters:@{} successBlock:^(id  _Nullable result) {
        [SVProgressHUD dismiss];
        [self closeAction];
        [[AIUserInfoManager shareManager] clearUserInfo];
        [AIUnityInstance.instance pause:YES];
        NTFPost(DeleteOrLogoutNotification, nil);
        [KAppDelegate changeRootVc];
    } failedBlock:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
    } showHUD:NO];
}

//退出登录
-(void)logoutTheAccount{
    [SVProgressHUD show];
    [AIManager requestMethod:@"GET" url:api_customLogout parameters:@{} successBlock:^(id  _Nullable result) {
        [SVProgressHUD dismiss];
        [self closeAction];
        [[AIUserInfoManager shareManager] clearUserInfo];
        [AIUnityInstance.instance pause:YES];
        NTFPost(DeleteOrLogoutNotification, nil);
        [KAppDelegate changeRootVc];
    } failedBlock:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
    } showHUD:NO];
}

#pragma mark --------------- lazy ---------------
- (UIVisualEffectView *)blurView{
    if(!_blurView){
        UIBlurEffect *blurEffect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
        _blurView = [[UIVisualEffectView alloc] initWithEffect:blurEffect];
        _blurView.alpha = 1;
        _blurView.backgroundColor = [UIColor colorHex:@"#AAAAAA" alpha:0.3];
    }
    return _blurView;
}

- (UIButton *)closeBtn{
    if(!_closeBtn){
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_closeBtn setImage:KImaged(@"ai_main_close") forState:UIControlStateNormal];
        [_closeBtn addTarget:self action:@selector(closeAction) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}

-(void)closeAction{
    [self dissMissAction];
    if (self.closeBlock){
        self.closeBlock();
    }
}

- (AIGradientTabView *)tableView{
    if(!_tableView){
        _tableView = [[AIGradientTabView alloc] initWithFrame:CGRectMake(0,KNavigationBarHeight, KScreenWidth, KScreenHeight - KNavigationBarHeight) direction:AIGradualDirectionTop gradualValue:@.2f];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.tableHeaderView = self.titView;
        _tableView.tableFooterView = self.logOutView;
        self.titView.titleLbl.text = @"Setting";
    }
    return _tableView;
}

- (AIWalletTitleView *)titView{
    if(!_titView){
        _titView = [[AIWalletTitleView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, PTW(80))];
    }
    return _titView;
}

- (AISetLogOutView *)logOutView{
    if(!_logOutView){
        _logOutView = [[AISetLogOutView alloc] initWithFrame:CGRectMake(0, PTW(20), KScreenWidth, PTW(95))];
        WeakSelf(self);
        _logOutView.logOutBlock = ^{
            AISetLogoutAlertView *logout = [[AISetLogoutAlertView alloc] initWithType:1];
            [logout showInView:weakself.view];
            logout.confirmBlock = ^{
                [weakself logoutTheAccount];
            };
        };
    }
    return _logOutView;
}


@end
